﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Web_CartCheck : System.Web.UI.Page
{
    List<Bestlife.ERP.Entities.Cart_Item> shp = new List<Bestlife.ERP.Entities.Cart_Item>();
    Bestlife.ERP.BusinessRules.Shopping_Cart shoppingCheck;
    Boolean transact_Ok = false;
    int rcpt;
    string invoiceids="";
    string uid = "0";

    protected void Page_Load(object sender, EventArgs e)
    {

        //if (Session["cashier"] != null)
        //{


            Session["key"] = "~/img/Process/4.png";
            reBind();
            checkout.Visible = true;
            //backbutton.Visible = false;
            if (!IsPostBack)
            {

                //Bestlife.ERP.DataAccess.ReturncountForRecipt rsp = new Bestlife.ERP.DataAccess.ReturncountForRecipt();
                //rcpt = rsp.ReturnReciptID();
                //invoiceids = "BC" + rcpt.ToString();
                //repid.Text = invoiceids;
                //rciptidint.Text = rcpt.ToString();

            }



            string stinBank = Request.QueryString["k"];
            string ricid = Request.QueryString["bkid"];
            if (stinBank != null)
            {


                if ((stinBank.Equals("1")) && (invoiceids.Equals(ricid)))//check and Validate 
                {

                    Allprocess();
                    //Print Ricipt

                }
            }
        //}
        //else { Response.Redirect("Admin_Login.aspx"); }
    }

    #region Rebind

    public void reBind()
    {
        List<Bestlife.ERP.Entities.Return_to_R> listrtn = new List<Bestlife.ERP.Entities.Return_to_R>();
        List<Bestlife.ERP.Entities.Tocheck_To_cart> listrtntocheck = new List<Bestlife.ERP.Entities.Tocheck_To_cart>();
        listrtn.Clear();
        listrtntocheck.Clear();
        if (Session["cart"] != null)
        {
            shoppingCheck = (Bestlife.ERP.BusinessRules.Shopping_Cart)Session["cart"];

            if (Session["user"] == null)
            {
                uid = "0";
            }
            else
            {
                uid = Session["user"].ToString();
                Bestlife.ERP.Entities.E_Profile pro = Bestlife.ERP.DataAccess.DistributerAC.getallprofileinfo(uid);

                name.Text = pro.Name1;
                add1.Text = pro.Address11;
                add2.Text = pro.Address21;
                add3.Text = pro.Address31;
                mob.Text = pro.Contact1;
            }


            totp.Visible = false;
            totpv.Visible = false;
            totbv.Visible = false;
            if (shoppingCheck.Items.Count > 0)
            {
                totp.Visible = true;
                totpv.Visible = true;
                totbv.Visible = true;

                #region for check to cart

                listrtntocheck = shoppingCheck.checkTo_cart;
                GridView1.DataSource = listrtntocheck;
                GridView1.DataBind();

                #endregion

                #region to recipt 
                listrtn = shoppingCheck.reciptvalues;


                //GridView2.DataSource = listrtn;
                //GridView2.DataBind();
                Bestlife.ERP.DataAccess.Pricecheckup pchk = new Bestlife.ERP.DataAccess.Pricecheckup();

                totp.Text = "" + pchk.returnPrice(shoppingCheck.total.ToString());
                totpv.Text = "" +Math.Round(shoppingCheck.totalPoint_value,2);
                totbv.Text = "" +Math.Round(shoppingCheck.totalBusiness_Value,2);
                #endregion

            }
        }
    }
    #endregion

    protected void ASPxButton1_Click(object sender, EventArgs e)
    {


    }
    protected void ASPxButton2_Click(object sender, EventArgs e)
    {

    }

    #region All process Methord

    public Boolean Allprocess()
    {

        string u_name = Session["user"].ToString();

        #region Entities And DataAccess Class

        Bestlife.ERP.DataAccess.D_bonus bnus = new Bestlife.ERP.DataAccess.D_bonus();
        Bestlife.ERP.Entities.E_Bonus ebns = new Bestlife.ERP.Entities.E_Bonus();

        Bestlife.ERP.DataAccess.users Us = new Bestlife.ERP.DataAccess.users();

        Bestlife.ERP.Entities.E_UserPurchs eupchs = new Bestlife.ERP.Entities.E_UserPurchs();
        Bestlife.ERP.DataAccess.D_UserPurchase dupchs = new Bestlife.ERP.DataAccess.D_UserPurchase();


        #endregion

        string UId = Us.GetUserId(u_name); // Change by thanuja (14/06/2012)//change by chathuranga get userId Using user Username 
        //    uid.Text = UId;
        #region check bestlife or vandana
        Boolean Otheraccount = false;

        if (u_name.Equals("vandana"))
        {
            Otheraccount = true;
        }
        else if (u_name.Equals("bestlife"))
        {
            Otheraccount = true;
        }

        #endregion

        if (Otheraccount == false)
        {
            if (Us.GetUserTablest(UId))
            {

                Bestlife.ERP.Entities.E_Bonus bnsback = bnus.Getbonus(UId);

                #region assign values

                double pv = double.Parse(bnsback.Ppv.ToString());
                double bv = double.Parse(bnsback.Bv.ToString());
                double DbTprice = double.Parse(bnsback.T_sales.ToString());
                double DbTpv = double.Parse(bnsback.Tpv.ToString());
                double DbTbv = double.Parse(bnsback.Tbv.ToString());

                #endregion


                double sTp = DbTprice + double.Parse(totp.Text);
                double sTpv = DbTpv + double.Parse(totpv.Text);
                double sTbv = DbTbv + double.Parse(totbv.Text);
                double sbv = bv + double.Parse(totbv.Text);
                double spv = pv + double.Parse(totpv.Text);

                #region Update Bonus table
                Us.UpdateBonus(UId, sTp, sTpv, sTbv, double.Parse(totpv.Text), double.Parse(totbv.Text));//send All Product Pv n Bvs only
                #endregion

                #region Send Values to calculation_Daily methord

                Bestlife.ERP.DataAccess.calculation_Daily cals = new Bestlife.ERP.DataAccess.calculation_Daily();

                // Pass Values to the calculation_Dailys class :
                cals.calculation_Dailys(UId, double.Parse(totbv.Text), double.Parse(totpv.Text), double.Parse(totp.Text));


                #endregion

            }
            else
            {
                #region Insert To Bonus

                Bestlife.ERP.BusinessRules.Check_montlyPV checkmp = new Bestlife.ERP.BusinessRules.Check_montlyPV();
                int userst = checkmp.first_status(UId, double.Parse(totpv.Text));

                ebns.User_id = UId;
                ebns.Tpv = decimal.Parse(totpv.Text);
                ebns.Ppv = decimal.Parse(totpv.Text);
                ebns.Cpv = decimal.Parse("0");
                ebns.CPV_month = decimal.Parse("0");
                ebns.T_sales = decimal.Parse(totp.Text);
                ebns.T_commision = decimal.Parse("0");
                ebns.T_Lship = decimal.Parse("0");
                ebns.Subdealers_Id = "Not In Use";
                ebns.CPV_month = decimal.Parse("0");
                ebns.Bv = decimal.Parse(totbv.Text);
                ebns.User_Status = userst.ToString();
                ebns.Tbv = decimal.Parse(totbv.Text);
                ebns.Storebv = 0;
                ebns.Storepv = 0;
                ebns.Lship_Status = 0;
                ebns.Store_Lship = 0;
                ebns.Storecomm = 0;
                ebns.Usercreate = UId;
                ebns.Date_create = System.DateTime.Now;


                bool st = bnus.Bonus_Add(ebns);

                if (st)
                {
                    //msg insert ok
                }
                else
                {
                    // msg server or Sql Error 
                }


                #endregion

                #region Send Values to calculation_Daily methord

                Bestlife.ERP.DataAccess.calculation_Daily cals = new Bestlife.ERP.DataAccess.calculation_Daily();

                // Pass Values to the calculation_Dailys class :
                cals.calculation_Dailys(UId, double.Parse(totbv.Text), double.Parse(totpv.Text), double.Parse(totp.Text));


                #endregion
            }

            #region insert into Receipt Table
            Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

            recept.D_id = UId;
            recept.D_name = name.Text;
            //recept.Rcpt_no = rcpt;
            recept.Toatal_PV = totpv.Text;
            recept.Total_BV = totbv.Text;
            recept.Total_Price = totp.Text;
            recept.Cashier_name = Session["cashier"].ToString();
            recept.R_date = System.DateTime.Now;

            Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
            drcpt.inserttoReceipt(recept);


            #endregion

            #region Insert in to Tbl_UserPurchase

            string rcptnum = rcptno();

            //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
            //payment gateway information mst be there
            foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
            {
                eupchs.User_ID = UId;
                eupchs.Pro_Name1 = ct.Name;
                eupchs.ProID = ct.ID;
                eupchs.Code = ct.Code;
                eupchs.Qty = ct.Quantity;
                eupchs.Price = decimal.Parse(ct.Price.ToString());
                eupchs.PV = decimal.Parse(ct.PV.ToString());
                eupchs.BV = decimal.Parse(ct.BV.ToString());
                eupchs.User_Create = u_name;
                eupchs.Date_Create = System.DateTime.Now;
                eupchs.Last_modify = System.DateTime.Now;
                eupchs.Key_Timestamp = 1;
                eupchs.R_ids = rcptnum;
                bool st = dupchs.UserPurchase_Add(eupchs);


                #region to stock table

                Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                decimal result = stock.reduceStock(ct.Name, ct.Quantity);
                if (result != 0)
                {
                    Label2.Visible = true;
                    Label2.Text = "Available Quantity  " + result.ToString();
                    Button2.Visible = true;
                    Button1.Visible = false;

                }
                else
                {

                #endregion

                    if (st)
                    {
                        Button1.Visible = true;
                        checkout.Visible = false;
                        conf.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                        //Response.Redirect("Home.aspx");

                        //conf.Text = "Welcome To BestLife";

                        //backbutton.Visible = true;
                    }
                }
            }
            //dupchs.UserPurchase_Add();
            #endregion

        }
        else if (Otheraccount==true)
        {
            #region insert into Receipt Table if Vandana Or Bestlife

            Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

            recept.D_id = UId;
            recept.D_name = name.Text;
            //recept.Rcpt_no = rcpt;
            recept.Toatal_PV = totpv.Text;
            recept.Total_BV = totbv.Text;
            recept.Total_Price = totp.Text;
            recept.Cashier_name = Session["cashier"].ToString();
            recept.R_date = System.DateTime.Now;

            Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
            drcpt.inserttoReceipt(recept);


            #endregion

            #region Insert in to Tbl_UserPurchase if Vandana Or Bestlife

            string rcptnum = rcptno();

            //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
            //payment gateway information mst be there
            foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
            {
                eupchs.User_ID = UId;
                eupchs.Pro_Name1 = ct.Name;
                eupchs.ProID = ct.ID;
                eupchs.Code = ct.Code;
                eupchs.Qty = ct.Quantity;
                eupchs.Price = decimal.Parse(ct.Price.ToString());
                eupchs.PV = decimal.Parse(ct.PV.ToString());
                eupchs.BV = decimal.Parse(ct.BV.ToString());
                eupchs.User_Create = u_name;
                eupchs.Date_Create = System.DateTime.Now;
                eupchs.Last_modify = System.DateTime.Now;
                eupchs.Key_Timestamp = 1;
                eupchs.R_ids = rcptnum;
                bool st = dupchs.UserPurchase_Add(eupchs);


                #region to stock table

                Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                decimal result = stock.reduceStock(ct.Name, ct.Quantity);
                if (result != 0)
                {
                    Label2.Visible = true;
                    Label2.Text = "Available Quantity  " + result.ToString();
                    Button2.Visible = true;
                    Button1.Visible = false;

                }
                else
                {

                #endregion

                    if (st)
                    {
                        Button1.Visible = true;
                        checkout.Visible = false;
                        conf.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                        //Response.Redirect("Home.aspx");

                        //conf.Text = "Welcome To BestLife";

                        //backbutton.Visible = true;
                    }
                }
            }
            //dupchs.UserPurchase_Add();
            #endregion
        }
        return transact_Ok;    
    }
    #endregion

    protected void checkout_Click(object sender, EventArgs e)
    {
        try
        {

            checkout.Visible = false;
            if (Session["user"] != null)
            {
                
                     #region check payment gatway conditions

                Bestlife.ERP.DataAccess.ReturncountForRecipt rsp = new Bestlife.ERP.DataAccess.ReturncountForRecipt();

                //string invoiceids = rsp.ReturnReciptID().ToString();
                string invoiceNo = repid.Text;
                string Total_Val = totp.Text;
                string pass = "acc$89#kry1009@technoBP21";
                string i = "technoBP";

                string url = invoiceNo + Total_Val + i + pass;


                string EncryptedID = rsp.EncryptMd5(url);

                string pathurl = "http://online.bestlifeltd.com/?m=onlineinvoice&a=AccGateway&r=" + invoiceNo + "&v=" + Total_Val + "&i=" + i + "&k=" + EncryptedID + "";

                bool stcon = rsp.launchurl(pathurl);
                string stinBank = Request.QueryString["k"];
                #endregion
                 
            }
            else
            {
                Response.Redirect("Login.aspx");
                //       //redirect
               
            }
        }
        catch (Exception ee)
        {

        }
    }
    protected void backbutton_Click(object sender, EventArgs e)
    {
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       // string invoid="BC"+Session["recpt"].ToString();
        HttpContext.Current.Response.Redirect("invoice.aspx?rcptID=" + repid.Text);
    }

    public string rcptno() 
    {
        Bestlife.ERP.DataAccess.ReturncountForRecipt rsp = new Bestlife.ERP.DataAccess.ReturncountForRecipt();
        rcpt = rsp.ReturnReciptID();
        invoiceids = "BC" + rcpt.ToString();
        repid.Text = invoiceids;

        return invoiceids;
    
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Cart.aspx");
    }
}
    
